#include "config.h"
#include "fonts_manager.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
static int FreeTypeFontInit(char *pcFontFile, unsigned int dwFontSize);
static int FreeTypeGetFontBitmap(unsigned int dwCode, PT_FontBitMap ptFontBitMap);
static T_FontOpr g_tFreeTypeFontOpr = {
    .name = "freetype",
    .FontInit = FreeTypeFontInit,
    .GetFontBitmap = FreeTypeGetFontBitmap

};
static FT_Face g_tFace;
int FreeTypeFontInit(char *pcFontFile, unsigned int dwFontSize)
{
    int ret;
    FT_Library g_tLibrary;

    // FT_GlyphSlot g_tSlot;
    ret = FT_Init_FreeType(&g_tLibrary);
    if (ret)
    {
        DBG_PRINTF("FT_Init_FreeType error\n");
        return -1;
    }
    ret = FT_New_Face(g_tLibrary, pcFontFile, 0, &g_tFace);
    if (ret)
    {
        DBG_PRINTF("FT_New_Face error\n");
        return -1;
    }
    ret = FT_Set_Pixel_Sizes(g_tFace, dwFontSize, 0);
    if (ret)
    {
        DBG_PRINTF("FT_Set_Pixel_Sizes error\n");
        return -1;
    }
    // g_tSlot = g_tFace->glyph;

    return 0;
}
int FreeTypeGetFontBitmap(unsigned int dwCode, PT_FontBitMap ptFontBitMap)
{
    int ret;
    int iPenX = ptFontBitMap->iCurOriginX;
    int iPenY = ptFontBitMap->iCurOriginY;
    ret = FT_Load_Char(g_tFace, dwCode, FT_LOAD_RENDER | FT_LOAD_MONOCHROME);
    if (ret)
    {
        DBG_PRINTF("FT_Load_Char error\n");
        return -1;
    }
    ptFontBitMap->iXLeft = iPenX + g_tFace->glyph->bitmap_left;
    ptFontBitMap->iYTop = iPenY - g_tFace->glyph->bitmap_top;
    ptFontBitMap->iXMax = ptFontBitMap->iXLeft + g_tFace->glyph->bitmap.width;
    ptFontBitMap->iYMax = ptFontBitMap->iYTop + g_tFace->glyph->bitmap.rows;
    ptFontBitMap->iBpp = 1;
    ptFontBitMap->iPitch = g_tFace->glyph->bitmap.pitch;
    ptFontBitMap->iNextOriginX = iPenX + g_tFace->glyph->advance.x/64;
    ptFontBitMap->iNextOriginY = iPenY;

    ptFontBitMap->pucBuffer = g_tFace->glyph->bitmap.buffer;
    return 0;
}
int FreeTypeInit(void)
{
	return RegisterFontOpr(&g_tFreeTypeFontOpr);
}